<?php

namespace App\Transformers;

use App\Models\PhoneRecord;
use App\Models\RecordRemark;
use League\Fractal\TransformerAbstract;

class PhoneRecordTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['user','fsUser','recordRemark'];

    public function transform(PhoneRecord $phoneRecord)
    {
        $url = $phoneRecord->recording_time>0?$phoneRecord->recording_url:'';
        return [
            'id' => $phoneRecord->id,
            'recording_time'=> empty($phoneRecord->recording_time)?'':$phoneRecord->recording_time,
            'voice_url'=> empty($phoneRecord->voice_url)?$url:$phoneRecord->voice_url,
            'fs_user_id' => empty($phoneRecord->fs_user_id)?'':$phoneRecord->fs_user_id,
            'user_id' => $phoneRecord->user_id,
            'task_id' => $phoneRecord->task_id,
            'created_at' => $phoneRecord->created_at,
            'updated_at' => $phoneRecord->updated_at,
        ];
    }

    public function includeUser(PhoneRecord $phoneRecord)
    {
        return $this->nullOrItem($phoneRecord->user, new UserTransformer());
    }

    public function includeFsUser(PhoneRecord $phoneRecord)
    {
        return $this->nullOrItem($phoneRecord->fsUser, new FsUserTransformer());
    }

    public function includeRecordRemark(PhoneRecord $phoneRecord){
        return $this->nullOrItem($phoneRecord->recordRemark->sortByDesc('created_at')->first(), new RecordRemarkTransformer());
    }

    public function nullOrItem($data, $transformer)
    {
        if (is_null($data)) {
            return parent::null();
        } else {
            return parent::item($data, $transformer);
        }
    }
}
